package com.example.chapter9sp;

import androidx.appcompat.app.AppCompatActivity;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.util.Map;

public class MainActivity extends AppCompatActivity {
    private Button btnSave,btnRead,btnQuite;
    private TextView tvResult;
    SharedPreferences cy;
    SharedPreferences.Editor edit;
    private static final String USERNAME = "username";
    private static final String PASSWORD = "password";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btnSave = findViewById(R.id.btn_save);
        btnRead = findViewById(R.id.btn_read);
        btnQuite = findViewById(R.id.btn_quite);

        tvResult = findViewById(R.id.tv_result);

         cy = getSharedPreferences("cy", AppCompatActivity.MODE_PRIVATE);
        edit = cy.edit();
        btnSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                EditText uname = findViewById(R.id.et_name);
                String sname = uname.getText().toString();
                EditText passw = findViewById(R.id.et_password);
                String spassw = passw.getText().toString();

                edit.putString(USERNAME,sname);
                edit.putString(PASSWORD,spassw);
                if (edit.commit()){
                    Toast.makeText(MainActivity.this,"保存成功",Toast.LENGTH_LONG).show();
                }
            }
        });

        btnRead.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String uname = cy.getString(USERNAME,"默认");
                String passw = cy.getString(PASSWORD,"默认");
                String hha = cy.getString("haha","默认");
                Map<String, ?> all = cy.getAll();
                Log.e("TAG", "onClick: "+all.toString() );
                tvResult.setText("uname:"+uname+"\n"+"passw:"+passw+"\n"+"haha"+hha);
            }
        });
        btnQuite.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

            }
        });
    }
}